/**
 * @ngdoc module
 * @name news.controllers
 * @description
 *   新闻模块控制器
 */
angular.module('news.controllers', [])

/**
 * @ngdoc controller
 * @name NewsIndexCtrl
 * @module news.controllers
 * @description
 *   已发布列表页控制器
 */
  .controller('NewsIndexCtrl', function($scope, NewsIndex, News){
    $scope.list = NewsIndex;
    $scope.title = '已发布';

    $scope.refresh = function() {
      $scope.list.fetch({
        catid: 0,
        page: 0,
        search: ''
      }, true).finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
      });
    };


    $scope.open = function(n) {
      News.open(n, 'news.detail');
    };

    // 若没有页面缓存，重置查询条件，直接加载第一页的数据
    // 如果上一次的页面缓存为搜索结果，同样重置查询条件
    if(!$scope.list.hasNews() || $scope.list.params.search) {
      $scope.list.fetch({
        catid: 0,
        page: 0,
        search: ''
      }, true)
    }

  })

/**
 * @ngdoc controller
 * @name NewsUnreadCtrl
 * @module news.controllers
 * @description
 *   未读列表页控制器
 */
  .controller('NewsUnreadCtrl', function($scope, $ionicHistory, $state, IbPopup, NewsUnread, News){
    $scope.list = NewsUnread;
    $scope.title = '未读';

    $scope.refresh = function() {
      $scope.list.fetch({
        catid: 0,
        page: 0,
        search: ''
      }, true).finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
      });
    };

    $scope.open = function(n) {
      News.open(n, 'news.detail');
    };

    $scope.markRead = function(){
      IbPopup.confirm({
        title:'确定要将此分类新闻全部标记成已读？',
      }).then(function(flag){
        if(flag){
          News.readall().success($scope.refresh);
        }
      });
    };

    // 若没有页面缓存，重置查询条件，直接加载第一页的数据
    // 如果上一次的页面缓存为搜索结果，同样重置查询条件
    if(!$scope.list.hasNews() || $scope.list.params.search) {
      $scope.refresh();
    }
  })

/**
 * @ngdoc controller
 * @name NewsUnapprovalCtrl
 * @module news.controllers
 * @description
 *   未审核列表页控制器
 */
  .controller('NewsUnapprovalCtrl', function($scope, News){
    function load(num) {
      return  News.list({ type: 'notallow', page: num }).success(function(res){
        $scope.news = res.data;
        $scope.pages = res.pages;
      });
    }

    load();

    $scope.loadMore = function(){
      load($scope.pages.page + 1);
    };

    $scope.refresh = function() {
      load().finally(function() {
        $scope.$broadcast('scroll.refreshComplete');
      });
    };

    $scope.open = function(n) {
      News.open(n, 'news.approval');
    };
  })

/**
 * @ngdoc controller
 * @name NewsCategoryCtrl
 * @module news.controllers
 * @description
 *   分组页控制器
 */
  .controller('NewsCategoryCtrl', function($scope, $ionicScrollDelegate, News){
    News.category().success(function(res){
      var categoryList = res.data;
      $scope.histories = [];

      //加载新的列表；
      function loadNewsList(catid) {
        return News.list({ catid: catid }).success(function(res) {
          $scope.list = res.data;
        });
      }

      $scope.open = function(n) {
        News.open(n, 'news.detail');
      };

      function getCategories(category){
        var ret = [];
        angular.forEach(categoryList, function(_category) {
          if(_category.pid === category.catid) {
            ret.push(_category);
          }
        });
        return ret;
      }

      $scope.enterCategory = function(category){
        // 把当前目录放入历史里
        $scope.list = [];
        if($scope.currentCategory) {
          $scope.histories.push($scope.currentCategory);
        }

        if(category.catid !== '0'){
          loadNewsList(category.catid)
        }
        $scope.currentCategory = category;
        $scope.categories = getCategories(category);
      };

      //返回上一个
      $scope.back = function(){
        $scope.currentCategory = $scope.histories.pop();
        loadNewsList($scope.currentCategory.catid);
        $scope.categories = getCategories($scope.currentCategory);
      };

      $scope.toCategory = function(category){
        $scope.currentCategory = category;
        $scope.histories.splice($scope.histories.indexOf(category));
        loadNewsList($scope.currentCategory.catid);
        $scope.categories = getCategories($scope.currentCategory);
      };

      $scope.enterCategory({
        catid: '0',
        name: ' '
      });

      // 监听路径历史，自动将面包屑滚动到末端
      var breadcrumbScrollInstance = $ionicScrollDelegate.$getByHandle('news-breadcrumb-scroll');
      $scope.$watchCollection('histories', function() {
        breadcrumbScrollInstance.scrollBottom(true);
      });
    });

    // news-breadcrumb-scroll
  })

/**
 * @ngdoc controller
 * @name NewsDetailCtrl
 * @module news.controllers
 * @description
 *   新闻详细页控制器
 */
  .controller('NewsDetailCtrl', function($scope, $sce, $filter, $stateParams, $ionicActionSheet, $ionicModal, $ionicLoading, $ionicHistory, $ionicPopup, $state, dateFilter, userInfoFilter, IbPopup, Utils, News, NewsIndex) {
    $scope.news = {};

    News.get($stateParams.id)
      .success(function(res) {
        $scope.news = res.data;
      });

    function getCommentParams(articleid){
      return{
        articleid: articleid,
        isDesc: 1,
        limit: 9999
      }
    }

    News.getComments(getCommentParams($stateParams.id)).success(function(res){
      $scope.commentList = res.data;
    });

    $scope.showMore = function(){
      $scope.form = {};
      $ionicActionSheet.show({
        buttons:[
          { text: $scope.news.istop == '0' ?  '置顶' : '取消置顶' },
          { text: '移动' }
        ],
        buttonClicked:function(index){
          if(index === 0 ){
            var params ={
              articleids: $stateParams.id,
              topEndTime:  ''
            };
            if($scope.news.istop == '0'){
              $ionicPopup.show({
                template: ' <input type="date" data-tap-disabled="true" ng-model="form.topEndTime">',
                title: '过期时间',
                scope: $scope,
                buttons: [
                  { text: '取消' },
                  {
                    text: '确认',
                    type: 'button-positive',
                    onTap: function(e) {
                      if($scope.form.topEndTime){
                        params.topEndTime = dateFilter($scope.form.topEndTime, 'yyyy-MM-dd');
                        $ionicLoading.show();
                        News.top(params)
                          .success(function(res){
                            $scope.news.istop = '1';
                            NewsIndex.reset();
                            $ionicHistory.clearCache(['news.published']);
                          })
                          .finally($ionicLoading.hide);
                      }
                    }
                  }
                ]
              });
            } else{
              $ionicLoading.show();
              News.top(params)
                .success(function() {
                  $scope.news.istop = '0';
                })
                .finally($ionicLoading.hide);
            }
          }

          if(index === 1 ){
            $ionicModal.fromTemplateUrl('templates/news/news-move.html',{
              scope: $scope,
              animation:'slide-in-up'
            })
              .then(function(modal) {
                $scope.moveModel = modal;
                $scope.moveModel.show();
                $scope.catid = '';

                News.category().success(function(res){
                  $scope.categoryList = res.data;
                  var currentPid = 0;

                  //将分组整理成树结构
                  function categoryTree(categoryList, pid) {
                    var result = [], temp;
                    for (var i = 0; i < categoryList.length; i++) {
                      categoryList[i].checked = false;
                      categoryList[i].showChildrenList = true;

                      //首先找到pid 等于0的文件夹；
                      if (categoryList[i].pid == pid) {
                        temp = categoryTree(categoryList, categoryList[i].catid);
                        if (temp.length > 0) {
                          categoryList[i].childrenList = temp;
                        }
                        result.push(categoryList[i]);
                      }
                    }
                    return result;
                  }

                  $scope.categorys = categoryTree($scope.categoryList, currentPid);

                  $scope.selectCategory = function(item){
                    if(item.checked === true){
                      $scope.catid = item.catid
                      angular.forEach($scope.categoryList, function(category){
                        category.checked = false;
                      });
                      item.checked = true;
                    } else {
                      $scope.catid = '';
                    }
                  };

                  $scope.submit = function(){
                    var params = {
                      articleids: $scope.news.articleid,
                      catid: $scope.catid
                    };
                    $ionicLoading.show();
                    News.move(params).success(function(res){
                      $scope.moveModel.hide();
                      $ionicLoading.hide();

                      Utils.clearStateCacheAndGo('news.published');
                    });
                  }
                })
              })
          }
          return true;
        },
        destructiveText: '删除',
        cancelText: '取消',
        destructiveButtonClicked: function() {
          var params = {
            articleids:$scope.news.articleid
          };
          News.delete(params).success(function(res){
            Utils.clearStateCacheAndGo('news.published');
          })
        }
      })
    };

    $scope.openComment = function(type, cm){
      $ionicModal.fromTemplateUrl('templates/news/news-comment.html',{
        scope: $scope,
        animation:'slide-in-up'
      })
        .then(function(modal){
          $scope.comment = {};
          $scope.commentModal = modal;
          $scope.commentModal.show();
          if (type === 'reply'){
            $scope.comment.content = cm.touid ? '回复 @' + userInfoFilter(cm.uid,'realname') + ' : ': ''
          }

          $scope.submit = function(){
            var params = {
              type:type ,
              content: $scope.comment.content,
            };

            if(type === 'comment'){
              params.rowid = $scope.news.articleid;
            } else {
              params.tocid = cm.cid;
              // 如果直接回复评论，则
              if(cm.tocid === '0') {
                params.rowid = cm.cid;
                // 否则，如果回复评论下的回复，则
              } else {
                params.rowid = cm.rowid;
              }
            }


            News.addComment(params).success(function(res){
              $scope.commentModal.hide();
              $ionicLoading.show();
              News.getComments(getCommentParams($scope.news.articleid)).success(function(res){
                $ionicLoading.hide();
                $scope.commentList = res.data;
              });
            })
          };
        })
    };


    $scope.openCommentDetail = function(){
      $ionicModal.fromTemplateUrl('templates/news/news-comment-detail.html',{
        scope: $scope,
        animation: 'slide-in-up'
      })
        .then(function(modal) {
          $scope.commentTetailModal = modal;
          $scope.commentTetailModal.show();

            News.getComments(getCommentParams($scope.news.articleid)).success(function(res){
              $ionicLoading.show();
              if(res.isSuccess){
                $scope.commentList = res.data
              }
            }).finally($ionicLoading.hide)
        })
    };

    $scope.openReaderDetail = function(){
      $ionicModal.fromTemplateUrl('templates/news/news-reader-detail.html',{
        scope: $scope,
        animation: 'slide-in-up'
      })
        .then(function(modal) {
          $scope.readerTetailModal = modal;
          $scope.readerTetailModal.show();
          var params = {
            articleid :$scope.news.articleid
          };
          News.getReaders(params).success(function(res){
            $scope.readers = res.data;
          })
        })
    };
  })

  .controller('NewsApprovalCtrl',function($scope, $stateParams, $sce, $filter, $ionicActionSheet, $ionicHistory, $ionicLoading, $ionicPopup, $state, IbPopup, News){
    News.get($stateParams.id)
      .success(function(res) {
        $scope.news = res.data;
      });

    $scope.checkNews = function(){
      $scope.form = {};
      $ionicActionSheet.show({
        buttons:[
          { text: '通过'}
        ],
        buttonClicked:function(index){
          if(index === 0 ){
            $ionicLoading.show();
            News.verify({ articleids: $scope.news.articleid })
              .success(function(res){
                $ionicLoading.hide();
                if(res.isSuccess === false) {
                  alert(res.msg);
                } else {
                  IbPopup.alert({ title : '审核通过'})
                  $ionicHistory.clearCache([$ionicHistory.currentView().stateId]).then(function() {
                    $state.reload();
                  });
                }
              });

            return true;
          }
        },
        destructiveText: '退回',
        cancelText: '取消',
        destructiveButtonClicked: function() {
          $ionicPopup.show({
            template: '<input ng-model="form.reason">',
            title: '退回',
            scope: $scope,
            buttons: [
              { text: '取消' },
              {text: '确认',
                type: 'button-positive',
                onTap: function(e) {
                  var params ={
                    articleids: $scope.news.articleid,
                    reason: $scope.form.reason
                  };
                  News.back(params).success(function(res){
                    //判断当前的步骤是不是最后一步，如不是，剩下所有步骤的状态都设置成未审核；
                    $ionicHistory.clearCache([$ionicHistory.currentView().stateId]).then(function() {
                      $state.reload();
                    })
                  })
                }
              }
            ]
          });
          return true;
        }
      })
    }
  });